package com.bike.util;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by zhoumengkang on 15/1/16.
 */
public class StringHelper {
    private static final StringBuffer bufferNum = new StringBuffer("0123456789");


    public static String emojiFilter(String str) {
        if (StringHelper.isEmpty(str)) {
            return str;
        }
        String patternString = "([\\x{10000}-\\x{10ffff}\ud800-\udfff])";

        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(str);

        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            try {
                matcher.appendReplacement(sb, "[[EMOJI:" + URLEncoder.encode(matcher.group(1), "UTF-8") + "]]");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        matcher.appendTail(sb);

        return sb.toString();
    }

    public static String emojiRecovery(String str) {
        String patternString = "\\[\\[EMOJI:(.*?)\\]\\]";

        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(str);

        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            try {
                matcher.appendReplacement(sb, URLDecoder.decode(matcher.group(1), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        matcher.appendTail(sb);

        return sb.toString();
    }


    /**
     * 国际手机号 下面的拼装规则是根据我们使用的短信平台的电话号码的规则而设定的，如果换短信平台该规则也需要更改
     *
     * @return
     */
    public static String phoneNumFilter(String phoneNum) {
        String patternString = "^\\+(\\d+)-(\\d{2,})$";

        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(phoneNum);

        StringBuilder sb = new StringBuilder();
        // 国内的不需要区号 国外的带上区号
        while (matcher.find()) {
            if (matcher.group(1).equals(Integer.toString(86)) || matcher.group(1).equals("0" + Integer.toString(86))) {
                return matcher.group(2);
            } else {
                sb.append("00").append(matcher.group(1));
                if (matcher.group(2).startsWith("0")) {
                    sb.append(matcher.group(2).substring(1));
                } else {
                    sb.append(matcher.group(2));
                }
            }
        }

        return sb.toString();
    }

    /**
     * 生成随机的字符串
     *
     * @param length
     * @return
     */
    public static String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 生成随机数字
     *
     * @param length
     * @return
     */
    public static String getRandomNum(int length) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    /**
     * 过滤id 列表 如 1,2,3,zmk,4 => 1,2,3,4
     *
     * @param ids
     * @return
     */
    public static String idsFilter(String ids) {
        String filterIds = "";
        if (ids.indexOf(",") < 1) {
            return ids;
        } else {

            String idsArr[] = ids.split(",");
            for (int i = 0; i < idsArr.length; i++) {
                if (idsArr[i].matches("[0-9]+")) {
                    filterIds += "," + idsArr[i];
                }
            }
            return filterIds.substring(1, filterIds.length());
        }
    }

    /**
     * 检测 string 是否包含了违禁词
     *
     * @param string
     * @return
     */
    public static boolean isContainBlockWords(String string) {

//        Iterator<String> it = BlockWordsCache.blockWords.iterator();
//
//        while (it.hasNext()) {
//            Pattern pattern = Pattern.compile(".*?" + it.next() + ".*?");
//            Matcher matcher = pattern.matcher(string);
//            if(matcher.matches()){
//                return true;
//            }
//        }

        return false;
    }

    /**
     * 判断字符是否为空
     *
     * @param str
     * @return boolean
     */
    public static boolean isEmpty(String str) {
        if (str == null || "".equals(str.trim()) || "null".equalsIgnoreCase(str))
            return true;
        else
            return false;
    }

    public static String getTelNickname(String tel) {
        if (isEmpty(tel)) {
            return null;
        }
        String nickName = null;
        try {
            nickName = tel.substring(0, 3) + "****" + tel.substring(7, tel.length());
        } catch (Exception e) {
        }
        return nickName;
    }


    /**
     * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址;
     *
     * @param request
     * @return
     */
    public static String getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }

    public static int[] getMaxIndex(AtomicLong[] arr) {
        if (arr == null || arr.length == 0) {
            return null;//如果数组为空 或者是长度为0 就返回null
        }
        int maxIndex = 0;//那假设第一个元素为最大值 么下标设为0
        int[] arrnew = new int[2];//设置一个 长度为2的数组 用作记录 规定第一个元素存储最大值 第二个元素存储下标
        arrnew[0] = arr[maxIndex].intValue();
        arrnew[1] = maxIndex;
        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[maxIndex].intValue() < arr[i + 1].intValue()) {
                maxIndex = i + 1;
                arrnew[0] = arr[maxIndex].intValue();
                arrnew[1] = maxIndex;
            }
        }
        return arrnew;
    }

}
